package com.z.redis.command.impl.set;

import com.z.redis.RedisCore;
import com.z.redis.command.CommandType;
import com.z.redis.command.WriteCommand;
import com.z.redis.datatype.BytesWrapper;
import com.z.redis.datatype.RedisData;
import com.z.redis.datatype.RedisSet;
import com.z.redis.resp.BulkString;
import com.z.redis.resp.Resp;
import com.z.redis.resp.RespInt;
import io.netty.channel.ChannelHandlerContext;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 在set中添加元素
 */
public class Sadd implements WriteCommand {
    List<BytesWrapper> members;
    private BytesWrapper key;

    @Override
    public CommandType type(){
        return CommandType.sadd;
    }

    @Override
    public void setContent(Resp[] array){
        key = ((BulkString) array[1]).getContent();
        members = Stream.of(array)
                .skip(2).map(resp -> ((BulkString) resp).getContent())
                .collect(Collectors.toList());
    }

    @Override
    public void handle(ChannelHandlerContext ctx, RedisCore redisCore){
        RedisData redisData = redisCore.get(key);
        if(redisData == null){
            RedisSet redisSet = new RedisSet();
            int sadd = redisSet.sadd(members);
            redisCore.put(key, redisSet);
            ctx.writeAndFlush(new RespInt(sadd));
        }else if(redisData instanceof RedisSet){
            RedisSet redisSet = (RedisSet) redisData;
            int sadd = redisSet.sadd(members);
            ctx.writeAndFlush(new RespInt(sadd));
        }else{
            throw new IllegalStateException("key is not set");
        }
    }

    @Override
    public void handle(RedisCore redisCore){
        RedisData redisData = redisCore.get(key);
        if(redisData == null){
            RedisSet redisSet = new RedisSet();
            int sadd = redisSet.sadd(members);
            redisCore.put(key, redisSet);
        }else if(redisData instanceof RedisSet){
            RedisSet redisSet = (RedisSet) redisData;
            int sadd = redisSet.sadd(members);
        }else{
            throw new IllegalStateException("key is not set");
        }
    }
}
